package com.sky.utils;

import org.json.JSONArray;
import org.json.JSONObject;
import com.sky.properties.BaiduProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.util.UriUtils;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.LinkedHashMap;
import java.util.Map;


@Component
public class SearchHttpAK {
    @Autowired
    private BaiduProperties baiduProperties;

    public double Util(String address) throws Exception {
        SearchHttpAK snCal = new SearchHttpAK();

        Map locationParams = new LinkedHashMap<String, String>();
        locationParams.put("address", address);
        locationParams.put("output", "json");
        locationParams.put("ak", baiduProperties.getAK());
        locationParams.put("callback", "showLocation");

        String locationBuffer = snCal.requestGetAK(baiduProperties.getLocationURL(), locationParams);
        double[] res = snCal.handleLocationJson(locationBuffer);
        double lng = res[0];
        double lat = res[1];
        System.out.println("经度为：" + lng + "，纬度为：" + lat);
        //把经纬度转为字符串
        String lat1 = String.valueOf(lat);
        String lng1 = String.valueOf(lng);
        //用“,"拼接
        String mes = lat1 + "," + lng1;
        Map ComputeParams = new LinkedHashMap<String, String>();
        ComputeParams.put("output", "json");
        ComputeParams.put("origins", baiduProperties.getLat()+","+baiduProperties.getLng());
        ComputeParams.put("destinations", mes);
        ComputeParams.put("ak", baiduProperties.getAK());

        String ComputeBuffer = snCal.requestGetAK(baiduProperties.getComputeURL(), ComputeParams);
        double distance = snCal.handleComputeJson(ComputeBuffer);
        System.out.println("距离为：" + distance);
        return distance;
    }

    public String requestGetAK(String strUrl, Map<String, String> param) throws Exception {
        if (strUrl == null || strUrl.length() <= 0 || param == null || param.size() <= 0) {
            return null;
        }

        StringBuffer queryString = new StringBuffer();
        queryString.append(strUrl);
        for (Map.Entry<?, ?> pair : param.entrySet()) {
            queryString.append(pair.getKey() + "=");
            //    第一种方式使用的 jdk 自带的转码方式  第二种方式使用的 spring 的转码方法 两种均可
            //    queryString.append(URLEncoder.encode((String) pair.getValue(), "UTF-8").replace("+", "%20") + "&");
            queryString.append(UriUtils.encode((String) pair.getValue(), "UTF-8") + "&");
        }

        if (queryString.length() > 0) {
            queryString.deleteCharAt(queryString.length() - 1);
        }

        java.net.URL url = new URL(queryString.toString());
        System.out.println(queryString.toString());
        URLConnection httpConnection = (HttpURLConnection) url.openConnection();
        httpConnection.connect();

        InputStreamReader isr = new InputStreamReader(httpConnection.getInputStream());
        BufferedReader reader = new BufferedReader(isr);
        StringBuffer buffer = new StringBuffer();
        String line;
        while ((line = reader.readLine()) != null) {
            buffer.append(line);
        }
        reader.close();
        isr.close();
        System.out.println("AK: " + buffer.toString());
        return buffer.toString();
    }

    public double[] handleLocationJson(String jsonString) throws Exception {


        int startIndex = jsonString.indexOf('(') + 1;
        int endIndex = jsonString.lastIndexOf(')');
        jsonString = jsonString.substring(startIndex, endIndex);

        JSONObject jsonObject = new JSONObject(jsonString);
        JSONObject result = jsonObject.getJSONObject("result");
        JSONObject location = result.getJSONObject("location");

        double lng = location.getDouble("lng");
        double lat = location.getDouble("lat");
        double[] res = {lng, lat};
        return res;
    }

    public double handleComputeJson(String jsonString) throws Exception {
        JSONObject jsonObject = new JSONObject(jsonString);
        JSONArray resultArray = jsonObject.getJSONArray("result");
        JSONObject firstResult = resultArray.getJSONObject(0);
        JSONObject distance = firstResult.getJSONObject("distance");

        String distanceText = distance.getString("text");
        distanceText = distanceText.replace("公里", "");
        double distanceValue = Double.parseDouble(distanceText);
        return distanceValue;
    }

}